package com.lingnan.controller;


import com.lingnan.pojo.DTO.ResultDTO;
import com.lingnan.utils.AliOSSUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@CrossOrigin(origins = "*")

public class FileUploadController {

    @RequestMapping(method = RequestMethod.POST, value = "/upload")
    public ResultDTO upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String originalFileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID() + originalFileType;
        String url = AliOSSUtil.uploadFile(filename, file.getInputStream());
        return ResultDTO.success(url);
    }

    @PostMapping("/uploadUserAvatar")
    public String uploadUserAvatar(@RequestParam("file") MultipartFile file) {
        try {
            InputStream in = file.getInputStream();
            String objectName = "avatars/" + UUID.randomUUID() + file.getOriginalFilename();
            return AliOSSUtil.uploadFile(objectName, in);
        } catch (Exception e) {
            throw new RuntimeException("上传失败");
        }
    }
}

